import axios from "axios";
import store from "../store";

// create an axios instance
const service = axios.create({
  baseURL: "https://www.baidu.com", // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      store.commit("toast/showToast", "提交失败，请稍后重试");
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    store.commit("toast/showToast", "提交失败，请稍后重试");
    return Promise.reject(error);
  }
);

export default service;
